import { createBrowserRouter, redirect, RouteObject } from 'react-router-dom';
import { lazy, Suspense } from 'react';
import { useAuthStore } from '@/store/useAuthStore';
import { userRoutes } from './client';
import { adminRoutes } from './admin';
import LoadingSpinner from '@/components/LoadingSpinner';

// 页面组件导入
import Login from '@/pages/account/Login';
import Register from '@/pages/account/Register';
import NotFound from '@/pages/NotFound';

// 懒加载重组件
const ProblemSubmit = lazy(() => import('@/pages/share/problem/Submit'));
const PaperEditor = lazy(() => import('@/pages/admin/question/PaperEditor'));



// 自定义路由类型（导出供其他路由文件使用）
export type MyRouteObject = RouteObject & {
  breadcrumb?: string;
  children?: MyRouteObject[];
};

// 权限检查函数（导出供其他路由文件使用）
export const checkAuth = () => {
  return useAuthStore.getState().isAuthenticated;
};

export const checkAdminAuth = () => {
  const auth = useAuthStore.getState();
  
  // Check if user is authenticated and has admin privileges
  if (!auth.isAuthenticated || !auth.user) {
    return false;
  }
  
  // Check admin_type - anyone not "Regular User" is considered an admin
  const { admin_type } = auth.user;
  return admin_type !== "Regular User";
};

// 通用公共路由（登录、注册等）
const publicRoutes: MyRouteObject[] = [
  {
    path: '/login',
    element: <Login />,
    breadcrumb: '登录',
    loader: () => checkAuth() ? redirect('/') : null,
  },
  {
    path: '/register',
    element: <Register />,
    breadcrumb: '注册',
    loader: () => checkAuth() ? redirect('/') : null,
  },
  {
    path: '/logout',
    loader: () => {
      useAuthStore.getState().clearAuth();
      return redirect('/login');
    },
  },
  {
    path: '/problem/:id/submit',
    element: (
      <Suspense fallback={<LoadingSpinner tip="加载代码编辑器..." />}>
        <ProblemSubmit />
      </Suspense>
    ),
    breadcrumb: '提交代码',
    loader: () => checkAuth() ? null : redirect('/login'),
  },
  // 试卷编辑器（独立页面，不使用布局）
  {
    path: '/admin/question/paper/create',
    element: (
      <Suspense fallback={<LoadingSpinner tip="加载编辑器..." />}>
        <PaperEditor />
      </Suspense>
    ),
    breadcrumb: '创建试卷',
    loader: () => checkAdminAuth() ? null : redirect('/login'),
  },
  {
    path: '/admin/question/paper/edit/:id',
    element: (
      <Suspense fallback={<LoadingSpinner tip="加载编辑器..." />}>
        <PaperEditor />
      </Suspense>
    ),
    breadcrumb: '编辑试卷',
    loader: () => checkAdminAuth() ? null : redirect('/login'),
  },
  {
    path: '*',
    element: <NotFound />,
  },
];

// 合并所有路由
const routes: MyRouteObject[] = [
  ...publicRoutes,
  ...adminRoutes,
  ...userRoutes,
];

// 创建路由
const router = createBrowserRouter(routes);

export { routes };  // 导出路由配置以供包屑使用
export default router; 